package com.shqcjd.preinstallglass.ui.activity.preview;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.open.androidtvwidget.bridge.EffectNoDrawBridge;
import com.open.androidtvwidget.bridge.OpenEffectBridge;
import com.open.androidtvwidget.view.FrameMainLayout;
import com.open.androidtvwidget.view.MainUpView;
import com.orhanobut.logger.Logger;
import com.shqcjd.preinstallglass.R;
import com.shqcjd.preinstallglass.ui.activity.input.LoginNumberInputActivity;
import com.shqcjd.preinstallglass.ui.activity.remote.BigImageLoaderActivity;
import com.shqcjd.preinstallglass.ui.base.BaseActivity;
import com.shqcjd.preinstallglass.ui.base.BasePresenter;
import com.shqcjd.preinstallglass.util.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import uk.co.senab.photoview.PhotoView;

public class PreImageActivity extends BaseActivity {
    private final String mSampleMimeType = "image/jpeg";
    @BindView(R.id.ib_back)
    ImageButton ib_back;
    @BindView(R.id.tv_toolbar_center)
    TextView tvToolbarCenter;
    @BindView(R.id.iv_preimage)
    PhotoView ivPreimage;
    @BindView(R.id.btn_show_big)
    Button btnShowBig;

    private String url;
    private String name;
    private Context mContext;
    private File imgfile;

    @BindView(R.id.mainUpView1)
    MainUpView mMainUpView;
    @BindView(R.id.main_lay)
    FrameMainLayout main_lay11;
    OpenEffectBridge mOpenEffectBridge;
    View mOldFocus;


    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_pre_image;
    }

    @Override
    protected String getVoiceContent() {
        return "|返回|查看原图;";
    }

    @Override
    protected void onVoiceResult(String result) {
        Logger.i("识别结果:"+result);
        switch (result) {
            case "返回":
                ib_back.performClick();
                break;
            case "查看原图":
                btnShowBig.performClick();
                break;
        }
    }


    @Override
    public void init() {
        super.init();
        String imgurl = getIntent().getStringExtra("url");
        url = imgurl.replaceFirst("https", "http");
//        url = "http://mmbiz.qpic.cn/mmbiz/PwIlO51l7wuFyoFwAXfqPNETWCibjNACIt6ydN7vw8LeIwT7IjyG3eeribmK4rhibecvNKiaT2qeJRIWXLuKYPiaqtQ/0";
        name = getIntent().getStringExtra("name");
    }

    @Override
    public void initView() {
        super.initView();
        mContext = this;
        tvToolbarCenter.setText(name);
        ib_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Logger.i("======:"+url);
        Glide.with(this).load(url).into(ivPreimage);

        mMainUpView.setEffectBridge(new EffectNoDrawBridge());
        mOpenEffectBridge = (OpenEffectBridge) mMainUpView.getEffectBridge();
        Drawable testDrawable = null;
        mMainUpView.setUpRectDrawable(testDrawable); // 设置边框图片
        mMainUpView.setUpRectResource(R.drawable.test_rectangle); // 设置边框图片.


        main_lay11.getViewTreeObserver().addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
            @Override
            public void onGlobalFocusChanged(final View oldFocus, final View newFocus) {

                if (newFocus != null)
//                    newFocus.bringToFront(); // 防止放大的view被压在下面. (建议使用MainLayout)
                    mMainUpView.setFocusView(newFocus, mOldFocus, 1.0f);
                mOldFocus = newFocus; // 4.3以下需要自己保存.
                // 测试是否让边框绘制在下面，还是上面. (建议不要使用此函数)
//                if (newFocus != null) {
//                    testTopDemo(newFocus, scale);
//                }
            }
        });
    }


    @OnClick({R.id.ib_back, R.id.btn_show_big})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
                finish();
                break;
            case R.id.btn_show_big://查看大图
                checkPermissions();
                break;
        }
    }

    private void checkPermissions() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        )
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            downloadImg();
                        } else {
                        }
                    }
                });
    }

    private void downloadImg() {
        Observable.create(new ObservableOnSubscribe<File>() {
            @Override
            public void subscribe(ObservableEmitter<File> e) throws Exception {
                //通过gilde下载得到file文件
                e.onNext(Glide.with(mContext)
                        .load(url)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get());
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .flatMap(new Function<File, Observable<File>>() {
                    @Override
                    public Observable<File> apply(File file) throws Exception {
                        File pictureFolder = Environment.getExternalStorageDirectory();
                        //第二个参数为你想要保存的目录名称
                        File appDir = new File(pictureFolder, "guide_picture_save_path");
                        if (!appDir.exists()) {
                            appDir.mkdirs();
                        }
                        String fileName = System.currentTimeMillis() + ".jpg";
                        File destFile = new File(appDir, fileName);
                        //把gilde下载得到图片复制到定义好的目录中去
                        copy(file, destFile);

                        return Observable.just(new File(destFile.getPath()));
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<File>() {

                    @Override
                    public void onSubscribe(Disposable d) {
                        showWaitingDialog("正在下载图片");
                    }

                    @Override
                    public void onNext(File file) {
                        imgfile = file;
                        goPreview(file);
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitingDialog();
                        ToastUtils.showShort(mContext,"图片下载失败");
                    }

                    @Override
                    public void onComplete() {
                        hideWaitingDialog();
                    }
                });
    }

    /**
     * @param source 输入文件
     * @param target 输出文件
     */
    public void copy(File source, File target) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(source);
            fileOutputStream = new FileOutputStream(target);
            byte[] buffer = new byte[1024];
            while (fileInputStream.read(buffer) > 0) {
                fileOutputStream.write(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void goPreview(File file) {
        if (file == null) {
            ToastUtils.showShort(mContext, "图片下载失败!");
            return;
        }
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.addCategory(Intent.CATEGORY_DEFAULT);
//        intent.setDataAndType(Uri.fromFile(imgfile), mSampleMimeType);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//
//        //
//        // 可以选择控制视觉外观
//        //
//        intent.putExtra("page", "1"); // Open a specific page
//        intent.putExtra("zoom", "3"); // Open at a specific zoom level
//
//        startActivity(intent);

        Intent intent = new Intent(mContext,BigImageLoaderActivity.class);
//        intent.setDataAndType(Uri.fromFile(imgfile), mSampleMimeType);
        intent.putExtra("imgurl", Uri.fromFile(file).toString());
        startActivity(intent);
    }
}
